package com.leetcode.algorithms.two.problem14;

import org.junit.Test;

public class LongestCommonPrefix {
    @Test
    public void run(){
        String[] strs = {"aca", "cba"};
        System.out.println(longestCommonPrefix(strs));
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0)
            return "";
        if (strs.length == 1)
            return strs[0];
        StringBuilder sb = new StringBuilder();

        String curr = strs[0];
        if (curr.length() == 0)
            return "";
        for (int i = 1; i < strs.length; i++) {
            sb = new StringBuilder();
            int len = curr.length() < strs[i].length() ? curr.length() : strs[i].length();
            for (int j = 0; j < len; j++) {
                if (curr.charAt(j) == strs[i].charAt(j))
                    sb.append(curr.charAt(j));
                else
                    break;
            }
            curr = sb.toString();
        }
        return sb.toString();

    }
}
